package ru.picman;

import ru.picman.util.GreenThread;
import ru.picman.util.GreenThreadProcessor;

import android.os.Handler;
import android.os.Message;

public class GameLoop
             extends Handler
{
	
	public GameLoop(PicmanGame game) {
		this.processor = new GreenThreadProcessor();
		this.game = game;
	}
	
	public void start() {
		if (started)
			throw new IllegalStateException("Already started");
		started = true;
		sleep(0);
	}
	
	public void addThread(GreenThread thread) {
		if (thread == null)
			throw new NullPointerException("The thread is null");
		processor.start(thread);
	}
	
	public void pause()
	{
		started = false;
		
	}
	
	public void handleMessage(Message msg) {
		processor.tick(System.currentTimeMillis());
		game.tick();
		sleep(TICK_DELAY);
	}
	
	private void sleep(long time) {
		
		this.removeMessages(0);
		
		sendMessageDelayed(obtainMessage(0),time);
	}
	
	//
	
	private boolean                    started;
	
	private final PicmanGame               game;
	private final GreenThreadProcessor processor;
	
	public static final long           TICK_DELAY = 50;
}
